<template>
  <div class="quick-search">
    <el-card shadow="hover">
      <template #header>
        <div class="search-header">
          <span class="search-title">
            <el-icon><Search /></el-icon>
            快速查找
          </span>
          <el-button size="small" @click="clearSearch" v-if="hasSearch">
            <el-icon><CircleClose /></el-icon>
            清除
          </el-button>
        </div>
      </template>

      <!-- 搜索输入区域 -->
      <div class="search-input-area">
        <el-autocomplete
          v-model="searchKeyword"
          :fetch-suggestions="getSuggestions"
          :trigger-on-focus="false"
          placeholder="输入关键词快速搜索..."
          size="large"
          style="width: 100%"
          clearable
          @select="handleSuggestionSelect"
          @keyup.enter="handleSearch"
          @clear="clearSearch"
        >
          <template #prepend>
            <el-select 
              v-model="selectedField" 
              placeholder="选择字段" 
              style="width: 140px;"
              @change="updateSuggestions"
            >
              <el-option label="全部字段" value="" />
              <el-option-group label="常用字段">
                <el-option
                  v-for="field in commonFields"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-option-group>
              <el-option-group label="所有字段" v-if="otherFields.length > 0">
                <el-option
                  v-for="field in otherFields"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-option-group>
            </el-select>
          </template>
          
          <template #append>
            <el-button @click="handleSearch" :loading="searching">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
          
          <template #default="{ item }">
            <div class="suggestion-item">
              <span class="suggestion-value">{{ item.value }}</span>
              <span class="suggestion-field">{{ item.field }}</span>
              <span class="suggestion-count" v-if="item.count">{{ item.count }}条</span>
            </div>
          </template>
        </el-autocomplete>
      </div>

      <!-- 快速过滤选项 -->
      <div class="quick-filters" v-if="quickFilters.length > 0">
        <div class="filter-title">快速过滤:</div>
        <div class="filter-options">
          <el-check-tag
            v-for="filter in quickFilters"
            :key="filter.id"
            :checked="activeFilters.includes(filter.id)"
            @change="toggleFilter(filter.id)"
            class="filter-tag"
          >
            {{ filter.label }}
          </el-check-tag>
        </div>
      </div>

      <!-- 搜索历史 -->
      <div class="search-history" v-if="recentSearches.length > 0">
        <div class="history-title">最近搜索:</div>
        <div class="history-items">
          <el-tag
            v-for="(item, index) in recentSearches.slice(0, 8)"
            :key="index"
            class="history-tag"
            closable
            @click="selectRecentSearch(item)"
            @close="removeRecentSearch(index)"
          >
            <el-icon><Clock /></el-icon>
            {{ item.keyword }}
            <span v-if="item.field" class="history-field">@{{ item.field }}</span>
          </el-tag>
        </div>
      </div>

      <!-- 热门搜索 -->
      <div class="popular-searches" v-if="popularSearches.length > 0">
        <div class="popular-title">热门搜索:</div>
        <div class="popular-items">
          <el-tag
            v-for="(item, index) in popularSearches"
            :key="index"
            class="popular-tag"
            effect="plain"
            @click="selectPopularSearch(item)"
          >
            <el-icon><TrendCharts /></el-icon>
            {{ item.keyword }}
            <span class="popular-count">{{ item.count }}</span>
          </el-tag>
        </div>
      </div>

      <!-- 搜索提示 -->
      <div class="search-tips" v-if="showTips">
        <el-alert
          title="搜索提示"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <ul class="tips-list">
              <li>支持模糊搜索，如输入"张"可以找到所有包含"张"的记录</li>
              <li>选择特定字段可以提高搜索精度</li>
              <li>使用快速过滤可以快速筛选常见条件</li>
              <li>点击搜索建议可以快速选择</li>
            </ul>
          </template>
        </el-alert>
      </div>
    </el-card>

    <!-- 搜索结果摘要 -->
    <div class="search-result-summary" v-if="lastSearchResult">
      <el-result
        :icon="lastSearchResult.total > 0 ? 'success' : 'warning'"
        :title="getResultTitle()"
        :sub-title="getResultSubTitle()"
      >
        <template #extra>
          <el-button 
            type="primary" 
            @click="showAdvancedSearch"
            v-if="lastSearchResult.total === 0"
          >
            使用高级搜索
          </el-button>
          <el-button 
            type="success" 
            @click="exportResults"
            v-if="lastSearchResult.total > 0"
          >
            导出结果
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, CircleClose, Clock, TrendCharts 
} from '@element-plus/icons-vue'

const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  tableName: {
    type: String,
    required: true
  },
  tableData: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['search', 'advanced-search', 'export'])

const searching = ref(false)
const searchKeyword = ref('')
const selectedField = ref('')
const activeFilters = ref([])
const showTips = ref(true)
const lastSearchResult = ref(null)

// 最近搜索记录
const recentSearches = ref([])
// 热门搜索
const popularSearches = ref([])
// 搜索建议
const suggestions = ref([])

// 常用字段和其他字段
const commonFields = computed(() => {
  const common = ['建筑名称', '位置', '编码', '名称', 'ID', 'id']
  return props.columns
    .filter(col => common.some(c => col.Field.includes(c)))
    .map(col => ({ label: col.Field, value: col.Field }))
})

const otherFields = computed(() => {
  const commonFieldValues = commonFields.value.map(f => f.value)
  return props.columns
    .filter(col => !commonFieldValues.includes(col.Field))
    .filter(col => {
      const type = col.Type.toUpperCase()
      return !['TEXT', 'LONGTEXT', 'BLOB', 'JSON'].some(t => type.includes(t))
    })
    .map(col => ({ label: col.Field, value: col.Field }))
})

// 是否有搜索条件
const hasSearch = computed(() => {
  return searchKeyword.value.trim() || activeFilters.value.length > 0
})

// 快速过滤选项（根据表类型动态生成）
const quickFilters = computed(() => {
  const filters = []
  
  // 根据表名和字段动态生成过滤选项
  if (props.tableName.includes('住宅')) {
    filters.push(
      { id: 'is_school_district', label: '学区房', field: '是否学区房', value: true },
      { id: 'high_price', label: '高价位', field: '平均房价', operator: '>', value: 50000 }
    )
  } else if (props.tableName.includes('商业')) {
    filters.push(
      { id: 'high_traffic', label: '高客流量', field: '客流量', operator: '>', value: 1000 },
      { id: 'many_merchants', label: '商户密集', field: '商户数量', operator: '>', value: 20 }
    )
  } else if (props.tableName.includes('公共设施')) {
    filters.push(
      { id: 'hospital', label: '医院', field: '设施类型', value: '医院' },
      { id: 'school', label: '学校', field: '设施类型', value: '学校' },
      { id: 'government', label: '政府机构', field: '设施类型', value: '政府' }
    )
  }
  
  // 通用过滤选项
  const hasDateField = props.columns.some(col => 
    ['DATE', 'DATETIME', 'TIMESTAMP'].some(type => col.Type.toUpperCase().includes(type))
  )
  
  if (hasDateField) {
    filters.push(
      { id: 'recent', label: '最近更新', field: 'update_time', operator: '>', value: 'recent' }
    )
  }
  
  return filters
})

// 获取搜索建议
const getSuggestions = async (queryString, cb) => {
  if (!queryString || queryString.length < 2) {
    cb([])
    return
  }
  
  try {
    // 从当前表数据中获取建议
    const fieldToSearch = selectedField.value || getDefaultSearchField()
    const suggestions = []
    
    if (fieldToSearch && props.tableData.length > 0) {
      const values = new Set()
      props.tableData.forEach(row => {
        const value = row[fieldToSearch]
        if (value && value.toString().toLowerCase().includes(queryString.toLowerCase())) {
          values.add(value.toString())
        }
      })
      
      Array.from(values).slice(0, 10).forEach(value => {
        suggestions.push({
          value: value,
          field: fieldToSearch,
          count: props.tableData.filter(row => 
            row[fieldToSearch] && row[fieldToSearch].toString() === value
          ).length
        })
      })
    }
    
    // 添加历史搜索建议
    recentSearches.value.forEach(recent => {
      if (recent.keyword.toLowerCase().includes(queryString.toLowerCase())) {
        suggestions.push({
          value: recent.keyword,
          field: recent.field || '历史搜索',
          isHistory: true
        })
      }
    })
    
    cb(suggestions)
  } catch (error) {
    console.error('获取搜索建议失败:', error)
    cb([])
  }
}

// 获取默认搜索字段
const getDefaultSearchField = () => {
  const nameFields = ['建筑名称', '名称', 'name', '位置', 'location']
  for (const field of nameFields) {
    const found = props.columns.find(col => 
      col.Field.toLowerCase().includes(field.toLowerCase())
    )
    if (found) return found.Field
  }
  return props.columns[0]?.Field || ''
}

// 处理搜索建议选择
const handleSuggestionSelect = (item) => {
  searchKeyword.value = item.value
  if (item.field && !item.isHistory) {
    selectedField.value = item.field
  }
  handleSearch()
}

// 执行搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim() && activeFilters.value.length === 0) {
    ElMessage.warning('请输入搜索关键词或选择过滤条件')
    return
  }
  
  searching.value = true
  
  // 构建搜索参数
  const searchParams = {
    quickSearch: {
      text: searchKeyword.value.trim(),
      field: selectedField.value
    },
    filters: activeFilters.value.map(filterId => 
      quickFilters.value.find(f => f.id === filterId)
    ).filter(Boolean)
  }
  
  // 添加到搜索历史
  if (searchKeyword.value.trim()) {
    addToRecentSearches({
      keyword: searchKeyword.value.trim(),
      field: selectedField.value,
      timestamp: Date.now()
    })
  }
  
  // 触发搜索事件
  emit('search', searchParams)
  
  setTimeout(() => {
    searching.value = false
    // 模拟搜索结果
    lastSearchResult.value = {
      keyword: searchKeyword.value,
      field: selectedField.value,
      total: Math.floor(Math.random() * 50),
      time: Date.now()
    }
  }, 500)
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  selectedField.value = ''
  activeFilters.value = []
  lastSearchResult.value = null
  emit('search', { reset: true })
}

// 切换过滤器
const toggleFilter = (filterId) => {
  const index = activeFilters.value.indexOf(filterId)
  if (index > -1) {
    activeFilters.value.splice(index, 1)
  } else {
    activeFilters.value.push(filterId)
  }
  
  // 如果有激活的过滤器，自动执行搜索
  if (activeFilters.value.length > 0) {
    handleSearch()
  }
}

// 添加到最近搜索
const addToRecentSearches = (searchItem) => {
  // 移除重复项
  recentSearches.value = recentSearches.value.filter(item => 
    item.keyword !== searchItem.keyword || item.field !== searchItem.field
  )
  
  // 添加到开头
  recentSearches.value.unshift(searchItem)
  
  // 限制数量
  if (recentSearches.value.length > 10) {
    recentSearches.value = recentSearches.value.slice(0, 10)
  }
  
  // 保存到本地存储
  localStorage.setItem(
    `quick_search_history_${props.tableName}`, 
    JSON.stringify(recentSearches.value)
  )
}

// 选择最近搜索
const selectRecentSearch = (item) => {
  searchKeyword.value = item.keyword
  selectedField.value = item.field || ''
  handleSearch()
}

// 删除最近搜索
const removeRecentSearch = (index) => {
  recentSearches.value.splice(index, 1)
  localStorage.setItem(
    `quick_search_history_${props.tableName}`, 
    JSON.stringify(recentSearches.value)
  )
}

// 选择热门搜索
const selectPopularSearch = (item) => {
  searchKeyword.value = item.keyword
  handleSearch()
}

// 更新建议
const updateSuggestions = () => {
  suggestions.value = []
}

// 显示高级搜索
const showAdvancedSearch = () => {
  emit('advanced-search')
}

// 导出结果
const exportResults = () => {
  emit('export')
}

// 获取结果标题
const getResultTitle = () => {
  if (!lastSearchResult.value) return ''
  
  const { total, keyword } = lastSearchResult.value
  if (total > 0) {
    return `找到 ${total} 条结果`
  } else {
    return '没有找到匹配的结果'
  }
}

// 获取结果副标题
const getResultSubTitle = () => {
  if (!lastSearchResult.value) return ''
  
  const { keyword, field, total } = lastSearchResult.value
  let subtitle = `搜索关键词: "${keyword}"`
  
  if (field) {
    subtitle += ` (在字段"${field}"中)`
  }
  
  if (total === 0) {
    subtitle += '\n建议: 尝试使用不同的关键词或使用高级搜索功能'
  }
  
  return subtitle
}

// 加载保存的数据
const loadSavedData = () => {
  const savedHistory = localStorage.getItem(`quick_search_history_${props.tableName}`)
  if (savedHistory) {
    try {
      recentSearches.value = JSON.parse(savedHistory)
    } catch (e) {
      console.error('加载搜索历史失败:', e)
    }
  }
  
  // 生成模拟热门搜索
  if (props.tableName.includes('建筑')) {
    popularSearches.value = [
      { keyword: '住宅', count: 156 },
      { keyword: '商业', count: 89 },
      { keyword: '学区', count: 67 },
      { keyword: '公园', count: 45 }
    ]
  }
}

// 监听表名变化
watch(() => props.tableName, () => {
  clearSearch()
  loadSavedData()
}, { immediate: true })

// 监听显示提示
watch(hasSearch, (val) => {
  if (val) {
    showTips.value = false
  }
})

// 暴露方法给父组件
defineExpose({
  clearSearch,
  setSearchResult: (total) => {
    if (lastSearchResult.value) {
      lastSearchResult.value.total = total
    }
  }
})

// 初始化
onMounted(() => {
  loadSavedData()
})
</script>

<style scoped>
.quick-search {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.search-input-area {
  margin-bottom: 16px;
}

.suggestion-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.suggestion-value {
  font-weight: 500;
  color: #303133;
}

.suggestion-field {
  font-size: 12px;
  color: #909399;
}

.suggestion-count {
  font-size: 12px;
  color: #67c23a;
}

.quick-filters {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.filter-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.search-history,
.popular-searches {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #fafbfc;
  border-radius: 6px;
}

.history-title,
.popular-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.history-items,
.popular-items {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag,
.popular-tag {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
}

.history-tag:hover,
.popular-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-field {
  color: #909399;
  font-size: 12px;
}

.popular-count {
  color: #f56c6c;
  font-size: 12px;
  font-weight: 500;
}

.search-tips {
  margin-bottom: 16px;
}

.tips-list {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  font-size: 14px;
}

.tips-list li {
  margin-bottom: 4px;
}

.search-result-summary {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .filter-options,
  .history-items,
  .popular-items {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-tag,
  .history-tag,
  .popular-tag {
    justify-content: center;
  }
}
</style>
